$(document).ready(function(){
   $.ajaxSetup({
      cache: false,
      headers: { "cache-control": "no-cache"},
      pragma: "no-cache"
   });

   $.extend($.datepicker, {
      /* Overwrite datepicker _generateMonthYearHeader function. */
      _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
            secondary, monthNames, monthNamesShort) {
         var changeMonth = this._get(inst, 'changeMonth');
         var changeYear = this._get(inst, 'changeYear');
         var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
         var html = '<div class="ui-datepicker-title">';
         var monthHtml = '';
         // month selection
         if (secondary || !changeMonth)
            monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>';
         else {
            var inMinYear = (minDate && minDate.getFullYear() == drawYear);
            var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
            monthHtml += '<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">';
            //PIPAPAI: change 'month < 12' => 'month < monthNamesShort.length' to support quarter picker
            for (var month = 0; month < monthNamesShort.length; month++) {
               if ((!inMinYear || month >= minDate.getMonth()) &&
                     (!inMaxYear || month <= maxDate.getMonth()))
                  monthHtml += '<option value="' + month + '"' +
                     (month == drawMonth ? ' selected="selected"' : '') +
                     '>' + monthNamesShort[month] + '</option>';
            }
            monthHtml += '</select>';
         }
         if (!showMonthAfterYear)
            html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '');
         // year selection
         if ( !inst.yearshtml ) {
            inst.yearshtml = '';
            if (secondary || !changeYear)
               html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
            else {
               // determine range of years to display
               var years = this._get(inst, 'yearRange').split(':');
               var thisYear = new Date().getFullYear();
               var determineYear = function(value) {
                  var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
                     (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
                     parseInt(value, 10)));
                  return (isNaN(year) ? thisYear : year);
               };
               var year = determineYear(years[0]);
               var endYear = Math.max(year, determineYear(years[1] || ''));
               year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
               endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
               inst.yearshtml += '<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">';
               for (; year <= endYear; year++) {
                  inst.yearshtml += '<option value="' + year + '"' +
                     (year == drawYear ? ' selected="selected"' : '') +
                     '>' + year + '</option>';
               }
               inst.yearshtml += '</select>';

               html += inst.yearshtml;
               inst.yearshtml = null;
            }
         }
         html += this._get(inst, 'yearSuffix');
         if (showMonthAfterYear)
            html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml;
         html += '</div>'; // Close datepicker_header
         return html;
      }
   });

   jQuery.fn.dateSelect = function(method){
      var methods = {
         init: function(options) {
            this.dateTxtObj = $('.dateinput', this);
            this.starTxtObj = $('.startxt', this);
            this.endTxtObj = $('.endtxt', this);
            this.endTxtBoxObj = $('.endtxtbox', this);
            this.startObj = $('.start', this);
            this.endObj = $('.end', this);
            this.tostartObj = $('.tostart', this);
            this.toendObj = $('.toend', this);
            this.dateTypeObj = $('.datetype', this);
            this.arrowBoxObj = $('.arrowbox', this);
            this.arrowPrevObj = $('.arrowlt', this.arrowBoxObj);
            this.arrowNextObj = $('.arrowrt', this.arrowBoxObj);
            this.dateBtnsBox = $('.datebtnsbox', this);
            this.collectObj = $('a.startcollect', this);

            options = jQuery.extend({
               defaultType: 'month',
               contrast: false
            }, options || {});

            this.options = options;

            this.dateSelect('initDatebar', options);
            if(!options.contrast)
               this.dateSelect('initArrow');

            var datetype = this.dateTypeObj.val();
            if(!datetype){
               this.dateBtnsBox.find('a.' + options.defaultType).trigger('click');
            }else{
               this.dateSelect('makeDateText', datetype);
            }
         },
         getNowDate: function(){
            var nowDate = {}, now = new Date(), year = now.getFullYear(), month = now.getMonth(), day = now.getDate();
            var yesd = new Date(year, month, (day -1));
            nowDate.date = yesd;
            nowDate.year = nowDate.date.getFullYear();
            nowDate.month = nowDate.date.getMonth() + 1;
            nowDate.day = nowDate.date.getDate() + 1;
            nowDate.quarter = Math.ceil(nowDate.month/3);
            nowDate.minYear = nowDate.year - 3;
            nowDate.maxYear = nowDate.year;
            // nowDate.maxMonthDate = nowDate.year + padDate(nowDate.month);
            // nowDate.maxQuarterDate = nowDate.year + padDate(nowDate.quarter);
            return nowDate;
         },
         makeDateText: function(datetype){
            var self = this;
            var start = self.startObj.val(), end = self.endObj.val(), dateFormat = self.dateSelect('getDateFormat', datetype);
            if(!datetype || !start || !end)
               return false;

            var startDate = new Date(start.replace(/-/g, '/')), endDate = new Date(end.replace(/-/g, '/'));
            switch(datetype){
               case 'year':
                  self.starTxtObj.val($.datepicker.formatDate(dateFormat, startDate));
                  break;
               case 'month':
                  self.starTxtObj.val($.datepicker.formatDate(dateFormat, startDate));
                  break;
               case 'custom':
                  self.starTxtObj.val($.datepicker.formatDate(dateFormat, startDate));
                  self.endTxtObj.val($.datepicker.formatDate(dateFormat, endDate));
                  self.endTxtBoxObj.show();
                  self.arrowBoxObj.hide();
                  break;
               case 'quarter':
                  var year = startDate.getFullYear();
                  var month = startDate.getMonth() + 1;
                  var quarter = Math.ceil(month/3);
                  self.starTxtObj.val(year + '年第' + padDate(quarter) + '季度');
                  break;
               default:
                  break;
            }
            self.dateSelect('updateDate', self.starTxtObj, datetype);
            if(datetype == 'custom'){
               self.dateSelect('updateDate', self.endTxtObj, datetype);
            }
            self.dateBtnsBox.find('a.' + datetype).trigger('click');
         },
         initDatebar: function(options){
            var self = this;
            $(self.dateBtnsBox).on('click', 'a.timeselect', function(){
               var datetype = $(this).data('datetype');
               self.dateTypeObj.val(datetype);
               $(this).closest('li').addClass('cur_li').siblings().removeClass('cur_li');
               if(!options.contrast){
                  if(datetype == 'custom'){
                     self.collectObj.show();
                     self.endTxtBoxObj.show();
                     self.arrowBoxObj.hide();
                  }else{
                     self.collectObj.hide();
                     self.endTxtBoxObj.hide();
                     self.arrowBoxObj.show();
                  }
               }else{
                  self.collectObj.show();
                  self.endTxtBoxObj.show();
                  self.arrowBoxObj.hide();
                  self.dateBtnsBox.find('a.custom').parent().hide();
               }

               if($('#ppp_dateselect').length > 0)
                  $('#ppp_dateselect').hide();

               self.dateSelect('initDateplugin', datetype, options);

               if($.isFunction(options.onFinished))
                  options.onFinished();
            });
         },
         initArrow: function(options){
            var self = this;
            self.arrowBoxObj.on('click', '.arrowlt, .arrowrt', function(){
               if($(this).hasClass('blackgrey'))
                  return;

               var prev = $(this).hasClass('arrowlt') ? 1 : 0;
               var target = $(self.arrowBoxObj.data('target'), self);
               var year = parseInt(target.data('year')), month = parseInt(target.data('month')), quarter = parseInt(target.data('quarter'));
               var datetype = self.dateTypeObj.val(), dateFormat = self.dateSelect('getDateFormat', datetype);

               if(datetype == 'year'){
                  if(prev)
                     year--;
                  else
                     year++;

                  target.val($.datepicker.formatDate(dateFormat, new Date(year, 0, 1)));
               }else if(datetype == 'quarter'){
                  if(prev)
                     quarter--;
                  else
                     quarter++;
                  if(quarter==0){
                     year--;
                     quarter = 4;
                  }
                  if(quarter==5){
                     year++;
                     quarter = 1;
                  }

                  target.val($.datepicker.formatDate(dateFormat, new Date(year, quarter-1, 1)));
               }else if(datetype == 'month'){
                  if(prev)
                     month--;
                  else
                     month++;
                  if(month==0){
                     year--;
                     month = 12;
                  }
                  if(month==13){
                     year++;
                     month = 1;
                  }

                  target.val($.datepicker.formatDate(dateFormat, new Date(year, month-1, 1)));
               }

               if(datetype != 'custom')
                  self.dateSelect('updateDate', target, datetype);
               self.collectObj.trigger('click');
            });
         },
         resetArrow: function(){
            var self = this;
            var prevObj = self.arrowPrevObj, nextObj = self.arrowNextObj, datetype = self.dateTypeObj.val(), nowDate = self.dateSelect('getNowDate');
            var target = $(self.arrowBoxObj.data('target'), self), year = target.data('year'), month = target.data('month'), quarter = target.data('quarter');

            if(datetype == 'year'){
               if(year <= nowDate.minYear)
                  $(prevObj).addClass('blackgrey');
               else
                  $(prevObj).removeClass('blackgrey');

               if(year >= nowDate.maxYear)
                  $(nextObj).addClass('blackgrey');
               else
                  $(nextObj).removeClass('blackgrey');
            }else if(datetype == 'quarter'){
               if(year <= nowDate.minYear && quarter <= 1)
                  $(prevObj).addClass('blackgrey');
               else
                  $(prevObj).removeClass('blackgrey');
               if(year >= nowDate.maxYear && quarter >= nowDate.quarter)
                  $(nextObj).addClass('blackgrey');
               else
                  $(nextObj).removeClass('blackgrey');
            }else if(datetype == 'month'){
               if(year <= nowDate.minYear && month <= 1)
                  $(prevObj).addClass('blackgrey');
               else
                  $(prevObj).removeClass('blackgrey');
               if(year >= nowDate.maxYear && month >= nowDate.month)
                  $(nextObj).addClass('blackgrey');
               else
                  $(nextObj).removeClass('blackgrey');
            }
         },
         initDateplugin: function (datetype, options){
            var self = this, dateFormat = self.dateSelect('getDateFormat', datetype), nowDate = self.dateSelect('getNowDate');

            self.off('.dateplugin');
            self.dateTxtObj.datepicker('destroy').off('click');

            if (datetype == 'custom') {
               self.dateTxtObj.datepicker({
                  dateFormat: dateFormat,
                  changeYear: true,
                  changeMonth: true,
                  maxDate: '-1d',
                  yearRange: '-3:+0',
                  onSelect: function(dateText, inst){
                     self.dateSelect('updateDate', inst.input, datetype);
                  },
                  onClose: function(dateText, inst){
                     self.dateSelect('setMonthYearDate', inst.input, datetype);
                     if(datetype != 'custom' && !options.contrast)
                        self.collectObj.trigger('click');
                  },
                  onChangeMonthYear: function(year, month, inst){
                     self.dateSelect('setMonthYearDate', inst.input, datetype);
                  },
                  beforeShow: function(input, inst){
                     var datevalue, inputdate = $(input).val();
                     if(datetype == 'year'){
                        datevalue = inputdate.replace(/年/g, '') + '-01' + '-01';
                        inst.dpDiv.addClass('hide-month hide-day');
                     }else if(datetype == 'quarter'){
                        datevalue = inputdate.replace(/年第/g, '-').replace('季度', '') + '-01';
                        inst.dpDiv.removeClass('hide-month').addClass('hide-day');
                        var maxDate = new Date(nowDate.year, nowDate.quarter -1, 1);
                        $(this).datepicker('option', 'maxDate', maxDate);
                        $(this).datepicker('option', 'monthNamesShort', ['第1季度', '第2季度', '第3季度', '第4季度']);
                     }else if(datetype == 'month'){
                        datevalue = inputdate.replace(/年|月/g, '-') + '01';
                        inst.dpDiv.removeClass('hide-month').addClass('hide-day');
                     }else{
                        datevalue = inputdate.replace(/年|月/g, '-').replace('日', '');
                        inst.dpDiv.removeClass('hide-month').removeClass('hide-day');
                     }
                     if(inputdate.length>0){
                        try {
                           var defaultdate = $.datepicker.parseDate('yy-mm-dd', datevalue, inst.settings);
                           $(this).datepicker('option', 'defaultDate', defaultdate);
                           $(input).val(inputdate);
                        }
                        catch(e) {}
                     }
                  }
               });

               self.dateTxtObj.click(function(){
                  $(this).datepicker('show');
               });
            }else{
               if($('#ppp_dateselect').length <= 0){
                  var yearul = '<ul class="pull-left">';
                  var quarterdiv = '<div class="ppp_timepicker_right pull-left">';
                  var monthdiv = '<div class="ppp_timepicker_right pull-left">';
                  for(tyear=nowDate.year; tyear>=nowDate.minYear; tyear--){
                     yearul += '<li class="year" data-year="' + tyear + '">' + tyear + '</li>';
                     quarterdiv += '<div class="ptr_eachquarter clearfix">';
                     for(tquarter=1; tquarter<=4; tquarter++){
                        disable_quarter = (tyear==nowDate.year && tquarter>nowDate.quarter);
                        quarterdiv += '<div class="pull-left"><a href="javascript:;"' + (disable_quarter ? 'class="notsldcur_a"' : 'class="quarter" data-quarter="' + tquarter + '"') + '>第' + tquarter + '季度</a></div>';
                     }
                     quarterdiv += '</div>';
                     monthdiv += '<div class="ptr_eachmonth clearfix">';
                     for(tmonth=1; tmonth<=12; tmonth++){
                        disable_month = (tyear==nowDate.year && tmonth>nowDate.month);
                        monthdiv += '<div class="pull-left"><a href="javascript:;" ' + (disable_month ? 'class="notsldcur_a"' : 'class="month" data-month="' + tmonth + '"') + '>' + tmonth + '</a></div>';
                     }
                     monthdiv += '</div>';
                  }
                  yearul += '</ul>';
                  quarterdiv += '</div>';
                  var yearhtml = '<div class="ppp_timepicker ppp_timepicker_year clearfix">' + yearul + '</div>';
                  var quarterhtml = '<div class="ppp_timepicker ppp_timepicker_quarter clearfix">' + yearul + quarterdiv + '</div>';
                  var monthhtml = '<div class="ppp_timepicker ppp_timepicker_month clearfix">' + yearul + monthdiv + '</div>';
                  var datehtml = '<div id="ppp_dateselect" class="ppp_timepickerwrap popup hide">' + yearhtml + quarterhtml + monthhtml + '</div>';
                  $('body').append(datehtml);

                  // to mark which is the min view unit
                  $('#ppp_dateselect .ppp_timepicker_year .year').addClass('minview');
                  $('#ppp_dateselect .ppp_timepicker_quarter .quarter').addClass('minview');
                  $('#ppp_dateselect .ppp_timepicker_month .month').addClass('minview');

                  $('#ppp_dateselect').on('click', '.ppp_timepicker ul li',function(){
                     var indexnum = $(this).index();
                     $(this).addClass('sldcur_li').siblings().removeClass('sldcur_li');
                     $(this).closest('ul').next('.ppp_timepicker_right').children().eq(indexnum).show().siblings().hide();
                  });
               }

               var dateTxtSelector = !options.contrast ? '.startxt' : '.dateinput';
               self.on('click.dateplugin', dateTxtSelector, function(){
                  var input = $(this);
                  inputdate = $(this).val();
                  if(datetype == 'year'){
                     datevalue = inputdate.replace(/年/g, '');
                     $('#ppp_dateselect .ppp_timepicker_year .year[data-year='+datevalue+']').addClass('sldcur_li').siblings().removeClass('sldcur_li');
                  }else if(datetype == 'quarter'){
                     datevalue = inputdate.replace(/年第/g, '-').replace('季度', '');
                     datevalue = datevalue.split('-');
                     var yearindex = $('#ppp_dateselect .ppp_timepicker_quarter .year[data-year='+datevalue[0]+']').index();
                     $('#ppp_dateselect .ppp_timepicker_quarter .year').eq(yearindex).addClass('sldcur_li').siblings().removeClass('sldcur_li');
                     $('#ppp_dateselect .ppp_timepicker_quarter .ptr_eachquarter .quarter').removeClass('sldcur_a');
                     $('#ppp_dateselect .ppp_timepicker_quarter .ptr_eachquarter:eq('+yearindex+') .quarter[data-quarter='+datevalue[1]+']').addClass('sldcur_a').siblings().removeClass('sldcur_a');
                     $('#ppp_dateselect .ppp_timepicker_quarter .ptr_eachquarter').eq(yearindex).show().siblings().hide();
                  }else if(datetype == 'month'){
                     datevalue = inputdate.replace(/年|月/g, '-');
                     datevalue = datevalue.split('-');
                     var yearindex = $('#ppp_dateselect .ppp_timepicker_month .year[data-year='+datevalue[0]+']').index();
                     $('#ppp_dateselect .ppp_timepicker_month .year').eq(yearindex).addClass('sldcur_li').siblings().removeClass('sldcur_li');
                     $('#ppp_dateselect .ppp_timepicker_month .ptr_eachmonth .month').removeClass('sldcur_a');
                     $('#ppp_dateselect .ppp_timepicker_month .ptr_eachmonth:eq('+yearindex+') .month[data-month='+datevalue[1]+']').addClass('sldcur_a').siblings().removeClass('sldcur_a');
                     $('#ppp_dateselect .ppp_timepicker_month .ptr_eachmonth').eq(yearindex).show().siblings().hide();
                  }

                  $('#ppp_dateselect .ppp_timepicker_' + datetype).show().siblings().hide();
                  $('#ppp_dateselect').show().position({
                     of: $(this),
                     my: 'left top',
                     at: 'left bottom'
                  });
                  
                  $('#ppp_dateselect').off('.ppp_dateselect').on('click.ppp_dateselect', '.minview', function(){
                     if (datetype == 'year') {
                        input.val($.datepicker.formatDate(dateFormat, new Date($(this).data(datetype), 1, 1)));
                     } else {
                        var selyear = $(this).closest('.ppp_timepicker').find('.year.sldcur_li').data('year');
                        input.val($.datepicker.formatDate(dateFormat, new Date(selyear, $(this).data(datetype)-1, 1)));
                     }
                     $(dateTxtSelector, self).each(function(){
                        self.dateSelect('updateDate', $(this), datetype);
                     });
                     $('#ppp_dateselect').hide();
                     if (!options.contrast)
                        self.collectObj.trigger('click');
                  });
               });
            }

            var default_startdate = self.starTxtObj.data('last_' + datetype + '_date'), default_endate = self.endTxtObj.data('last_' + datetype + '_date');

            if(!options.contrast){
               if(datetype == 'year' || datetype == 'month'){
                  if(!default_startdate)
                     default_startdate = $.datepicker.formatDate(dateFormat, nowDate.date);
               }else if(datetype == 'quarter'){
                  if(!default_startdate)
                     default_startdate = $.datepicker.formatDate(dateFormat, new Date(nowDate.year, nowDate.quarter-1, 1));
               }else if(datetype == 'custom'){
                  if(!default_startdate)
                     default_startdate = $.datepicker.formatDate(dateFormat, new Date(nowDate.year, nowDate.month-2, nowDate.day-1));
                  if(!default_endate)
                     default_endate = $.datepicker.formatDate(dateFormat, nowDate.date);
               }
            }else{
               if(datetype == 'year' || datetype == 'month'){
                  if(!default_startdate)
                     default_startdate = $.datepicker.formatDate(dateFormat, nowDate.date);
                  if (!default_endate) {
                     if (datetype == 'year') {
                        default_endate = $.datepicker.formatDate(dateFormat, new Date(nowDate.year-1, 0, 1));
                     } else {
                        default_endate = $.datepicker.formatDate(dateFormat, new Date(nowDate.year, nowDate.month-2, 1));
                     }
                  }
               }else if(datetype == 'quarter'){
                  if(!default_startdate)
                     default_startdate = $.datepicker.formatDate(dateFormat, new Date(nowDate.year, nowDate.quarter-1, 1));
                  if(!default_endate){
                     if (nowDate.quarter >= 2)
                        default_endate = $.datepicker.formatDate(dateFormat, new Date(nowDate.year, nowDate.quarter-2, 1));
                     else
                        default_endate = $.datepicker.formatDate(dateFormat, new Date(nowDate.year-1, 3, 1));
                  }
               }
            }

            self.starTxtObj.val(default_startdate);
            self.dateSelect('updateDate', self.starTxtObj, datetype);
            if (!options.contrast) {
               if(datetype == 'custom'){
                  self.endTxtObj.val(default_endate);
                  self.dateSelect('updateDate', self.endTxtObj, datetype);
               }
            } else {
               self.endTxtObj.val(default_endate);
               self.dateSelect('updateDate', self.endTxtObj, datetype)
            }
            
         },
         updateDate: function(input, datetype){
            var start, end, self = this, options = self.options;
            var date = $(input).val(), lastdate = date, nowDate = self.dateSelect('getNowDate');
            if (!options.contrast) {
               if(datetype == 'year'){
                  date = parseInt(date.replace(/年/g, ''));
                  start = $.datepicker.formatDate('yy-mm-dd', new Date(date, 0, 1));
                  end = new Date(date+1, 0, 0);
                  // for year, we always show a full year range to make the line chart eazy to understand
                  // end = end > nowDate.date ? nowDate.date : end;
                  end = $.datepicker.formatDate('yy-mm-dd', end);
                  self.startObj.val(start);
                  self.endObj.val(end);
                  $(input).data('year', date);
               }else if(datetype == 'quarter'){
                  date = date.replace(/年第/g, '-').replace('季度', '') + '-01';
                  var dates = date.split('-');
                  if(dates.length >1){
                     var year = parseInt(dates[0]);
                     var quarter = parseInt(dates[1]);
                     var minMonth = (quarter-1)*3;
                     var maxMonth = quarter*3;
                     start = $.datepicker.formatDate('yy-mm-dd', new Date(year, minMonth, 1));
                     end = new Date(year, maxMonth, 0);
                     // for quarter, we always show a full quarter range to make the line chart eazy to understand
                     // end = end > nowDate.date ? nowDate.date : end;
                     end = $.datepicker.formatDate('yy-mm-dd', end);
                     self.startObj.val(start);
                     self.endObj.val(end);
                     $(input).data({year: year, quarter: quarter});
                  }
               }else if(datetype == 'month'){
                  date = date.replace(/年|月/g, '-') + '01';
                  var dates = date.split('-');
                  if(dates.length >1){
                     var year = parseInt(dates[0]);
                     var month = parseInt(dates[1].replace(/^0*/, ''));
                     start = $.datepicker.formatDate('yy-mm-dd', new Date(year, month-1, 1));
                     end = new Date(year, month, 0);
                     // for month, we always show a full month range to make the line chart eazy to understand
                     // end = end > nowDate.date ? nowDate.date : end;
                     end = $.datepicker.formatDate('yy-mm-dd', end);
                     self.startObj.val(start);
                     self.endObj.val(end);
                     $(input).data({year: year, month: month});
                  }
               }else if(datetype == 'custom'){
                  date = date.replace(/年|月/g, '-').replace('日', '');
                  dates = date.split('-');
                  date = $.datepicker.formatDate('yy-mm-dd', new Date(dates[0], dates[1]-1, dates[2]));
                  var target = $($(input).data('target'), self);
                  if(target.length > 0)
                     target.val(date);
               }
               $(input).data('last_' + datetype + '_date', lastdate);
               if($(input).data('arrow'))
                  self.dateSelect('resetArrow');
            } else {
               if(datetype == 'year'){
                  date = parseInt(date.replace(/年/g, ''));
                  start = $.datepicker.formatDate('yy-mm-dd', new Date(date, 0, 1));
                  end = new Date(date+1, 0, 0);
                  end = end > nowDate.date ? nowDate.date : end;
                  end = $.datepicker.formatDate('yy-mm-dd', end);
                  if ($(input).hasClass('startxt')) {
                     self.startObj.val(start);
                     self.endObj.val(end);
                  }
                  if ($(input).hasClass('endtxt')) {
                     self.tostartObj.val(start);
                     self.toendObj.val(end);
                  }
                  $(input).data('year', date);
               }else if(datetype == 'quarter'){
                  date = date.replace(/年第/g, '-').replace('季度', '') + '-01';
                  var dates = date.split('-');
                  if(dates.length >1){
                     var year = parseInt(dates[0]);
                     var quarter = parseInt(dates[1]);
                     var minMonth = (quarter-1)*3;
                     var maxMonth = quarter*3;
                     start = $.datepicker.formatDate('yy-mm-dd', new Date(year, minMonth, 1));
                     end = new Date(year, maxMonth, 0);
                     end = end > nowDate.date ? nowDate.date : end;
                     end = $.datepicker.formatDate('yy-mm-dd', end);
                     if ($(input).hasClass('startxt')) {
                        self.startObj.val(start);
                        self.endObj.val(end);
                     }
                     if ($(input).hasClass('endtxt')) {
                        self.tostartObj.val(start);
                        self.toendObj.val(end);
                     }
                     $(input).data({year: year, quarter: quarter});
                  }
               }else if(datetype == 'month'){
                  date = date.replace(/年|月/g, '-') + '01';
                  var dates = date.split('-');
                  if(dates.length >1){
                     var year = parseInt(dates[0]);
                     var month = parseInt(dates[1]);
                     start = $.datepicker.formatDate('yy-mm-dd', new Date(year, month-1, 1));
                     end = new Date(year, month, 0);
                     end = end > nowDate.date ? nowDate.date : end;
                     end = $.datepicker.formatDate('yy-mm-dd', end);
                     if ($(input).hasClass('startxt')) {
                        self.startObj.val(start);
                        self.endObj.val(end);
                     }
                     if ($(input).hasClass('endtxt')) {
                        self.tostartObj.val(start);
                        self.toendObj.val(end);
                     }
                     $(input).data({year: year, month: month});
                  }
               }
            }
         },
         setMonthYearDate: function(input, datetype){
            var self = this;
            if(datetype != 'custom'){
               var month = $('#ui-datepicker-div .ui-datepicker-month :selected').val();
               var year = $('#ui-datepicker-div .ui-datepicker-year :selected').val();
               $(input).datepicker('setDate', new Date(year, month, 1));
               self.dateSelect('updateDate', input, datetype);
            }
         },
         getDateFormat: function(datetype){
            var dateFormat;
            switch(datetype){
               case 'year':
                  dateFormat = 'yy年';
                  break;
               case 'month':
                  dateFormat = 'yy年m月';
                  break;
               case 'custom':
                  dateFormat = 'yy年m月d日';
                  break;
               case 'quarter':
                  dateFormat = 'yy年第m季度';
                  break;
               default:
                  dateFormat = 'yy-m-d';
                  break;
            }
            return dateFormat;
         }
      };

      if (methods[method]){
         return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
      }else if(typeof method === 'object' || !method){
         return methods.init.apply(this, arguments);
      }else{
         $.error('Method ' +  method + ' does not exist on dateSelect');
      }
   };

   $('.rep_innerwrap').on('click', 'a.startcollect', function(){
      var target = $(this), form = $(this).closest('form'), container = form.data('container'), data = {};
      $('.cns', form).each(function(){
         var name = $(this).attr('name'), val = $(this).val();
         data[name] = val;
      });
      $(this).closest('form').ajaxSubmit({
         data: data,
         beforeSubmit: function(data, form, options) {
            var start = $('.start', form).val(), end = $('.end', form).val();
            if(start > end){
               showMessagePanel('开始时间不能大于结束时间', target, true, {placement:'bottom'});
               return false;
            }

            if (!showLoading($(container).css('minHeight', 150), options, {top: 500}, {button:true}))
               return false;
         },
         success: function(result, status, xhr, form) {
            $(container).css('minHeight', 'auto').html(result);
            resizeAppHeight();
         }
      });
      return false;
   });

   $('.rep_innerwrap.common .datebar:visible').each(function(){
      var datebar = $(this);
      $(this).dateSelect({
         defaultType: 'custom',
         onFinished: function(){
            $('a.startcollect', datebar).trigger('click');
         }
      });
   });

   $(document).bind('keydown', function(event) {
      if(event.keyCode == 27) {
         $(".popup").hide();
         return true;
      }
   });

   $(document).bind('mousedown', function(e){
      e = $.event.fix(e);
      var otarget = $(e.target);
      if(otarget.closest(".popup").length>0) {
         if(otarget.hasClass("closediv")) {
            otarget.closest(".popup").hide();
            return true;
         }
         return true;
      }    
      // close all popup that no need keep and dropdown by open class
      $('.popup').not('.keepopen').hide().closest('.dropdown.open').removeClass('open');
      return true;
   });

   $(document).on("click",".rep_sumtop a.linkto",function(){
      var anchor = $($(this).data('anchor'));
      var winwidth = $(window).width();
      if(winwidth<=1233){
         $('html,body').animate({scrollTop:anchor.offset().top-10},1000);
      }else{
         $('html,body').animate({scrollTop:anchor.offset().top-190},1000);
      }
      anchor.find('h5').css('backgroundColor','#aee7f9').animate({backgroundColor:'#e8f5f9'},500);
   });

   $(document).on("click","#rpos_createpos",function(){
      var scrolltop = $(window).scrollTop();
      $("#report_createpos_dialog").css({top:scrolltop+75}).modal();
   });

   $('.folderSelect').on('click', '.folder', function(event){
      event.stopPropagation();
      var target=$(this), fid = target.data('fid'), url = $('#jobGroupNav').data('url');
      $.ajax({
         type: "POST",
         url: OC.filePath('reports', 'ajax', 'recordjobgroup.php'),
         data: {fid: fid},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if(result.status === 'success') {
               url = getUrlQuery(url, 'fid=' + fid);
               window.location.href = url;
            } else {
               showMessagePanel(result.data.message, target, true, {placement:'bottom'});
            }
         }
      });
   });

   $('#citySelect').on('click', '.city', function(event){
      event.stopPropagation();
      var target=$(this), cityid = target.data('cityid'), url = $('#jobGroupNav').data('url');
      $.ajax({
         type: "POST",
         url: OC.filePath('jobposition', 'ajax', 'savefolder.php'),
         data: {type: $('#jobGroupNav').data('type'), cityids: JSON.stringify([cityid]), source: 'jobgroup_internal'},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if(result.status === 'success') {
               url = getUrlQuery(url, 'fid=' + result.data);
               window.location.href = url;
            } else {
               showMessagePanel(result.data.message, target, true, {placement:'bottom'});
            }
         }
      });
   });

   /* disable dropdown for now
   $('#manageJobGroupModal').on('hidden', function(){
      if(!$(this).hasClass('sleeping'))
         $('#jobGroupNav').addClass('open');
   });
   */

   $('#jobGroupNav').on('click', '#manageJobGroup', function(){
      var scrolltop = $(window).scrollTop();
      var url = $('#jobGroupNav').data('url');
      $.ajax({
         type: 'GET',
         url: OC.filePath('jobposition', 'ajax', 'getjobgrouplist.php'),
         data: {url: url, type: $('#jobGroupNav').data('type')},
         cache: false,
         beforeSend: function(xhr, settings) {
            $('#manageJobGroupModal').css({top:scrolltop+75}).show();
            if(!showLoading($('#jobGroupList').css('minHeight', 150), settings, null, {button:true}))
               return false;
            $('#manageJobGroupModal').modal('show');
         },
         success: function(result) {
            $('#jobGroupList').css('minHeight', 'auto').html(result);
         }
      });
   });

   $('#jobGroupNav').on('click', '#createJobGroup', function(){
      var url = $('#jobGroupNav').data('url');
      $(this).jobTagSelect({
         title: '新建职位组',
         newMode: true,
         jobgroup: {type: $('#jobGroupNav').data('type'), redirect_url: url},
         button: true,
         tagselect: true,
         listurl: OC.filePath('company', 'ajax', 'getsubaccountsjoblist.php'),
         search: {url: OC.filePath('company', 'ajax', 'getsubaccountsjoblist.php') + '?q=%q'},
         hideCallback: function(){
            $(".popover").removeClass("in");
         }
      });
   });

   $('#manageJobGroupModal').on('click', '.edit', function(event){
      event.stopPropagation();
      var target = $(this);
      var td = $(this).closest('td');
      var fid = td.data('fid');
      var fname = td.data('fname');
      var scrolltop = $(window).scrollTop();
      $.ajax({
         type: 'POST',
         url: OC.filePath('jobposition', 'ajax', 'getjobgroupdata.php'),
         data: {fid: fid},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if(result.status === 'success') {
               $('#manageJobGroupModal').addClass('sleeping').modal('hide');
               $(this).jobTagSelect({
                  title: '编辑职位组',
                  newMode: false,
                  jobgroup: {type: $('#jobGroupNav').data('type'), fid: fid, fname: fname},
                  button: true,
                  tagselect: true,
                  listurl: OC.filePath('company', 'ajax', 'getsubaccountsjoblist.php'),
                  search: {url: OC.filePath('company', 'ajax', 'getsubaccountsjoblist.php') + '?q=%q'},
                  defaultJobdata: result.data,
                  hideCallback: function(){
                     //$('#jobGroupNav').addClass('open');
                     $(".popover").removeClass("in");
                     if(fid == $('#jobGroupNav').data('fid')) {
                        window.location.href = getUrlQuery($('#jobGroupNav').data('url'), 'fid=' + fid);
                     } else {
                        $.ajax({
                           type: 'GET',
                           url: OC.filePath('jobposition', 'ajax', 'getjobgroupdropdown.php'),
                           data: {fid: $('#jobGroupNav').data('fid'), url: $('#jobGroupNav').data('url'), type: $('#jobGroupNav').data('type')},
                           cache: false,
                           success: function(result) {
                              $('#jobGroupNav').html(result);
                              $("label.key").each(function(i, el) { beautifyTableCaption(el); });
                           }
                        });
                     }
                  }
               });
            } else {
               showMessagePanel(result.data.message, target, true, {placement:'top'});
            }
         }
      });
   }).on('click', '.delete', function(event){
      event.stopPropagation();
      var target = $(this);
      var td = $(this).closest('td');
      var fid = td.data('fid');
      
      $('#manageJobGroupModal').addClass('sleeping').modal('hide');
      showConfirmDialog('确认删除该职位组合么？',function() {
         $.ajax({
            type: 'POST',
            url: OC.filePath('jobposition', 'ajax', 'removefolder.php'),
            data: {fid: fid},
            beforeSend: function(xhr, settings) {
               if(!showLoading(target, settings, null, {button:true}))
                  return false;
            },
            success: function(result){
               if (!isLoggedIn(result, target)) {
                  window.location = redirect_url;
                  return;
               }
               
               if(!$.isPlainObject(result)) {
                  result = $.parseJSON(result);
               }
               
               if(result.status === 'success') {
                  if(fid == $('#jobGroupNav').data('fid')) {
                     window.location = $('#jobGroupNav').data('url');
                  } else {
                     $.ajax({
                        type: 'GET',
                        url: OC.filePath('jobposition', 'ajax', 'getjobgrouplist.php'),
                        cache: false, 
                        beforeSend: function() {
                           if(!showLoading($('#jobGroupList')))
                              return false;
                        },
                        success: function(result) {
                           $('#jobGroupList').html(result);
                           $('#manageJobGroupModal').removeClass('sleeping').modal('show');
                           $.ajax({
                              type: 'GET',
                              url: OC.filePath('jobposition', 'ajax', 'getjobgroupdropdown.php'),
                              data: {fid: $('#jobGroupNav').data('fid'), url: $('#jobGroupNav').data('url'), type: $('#jobGroupNav').data('type')},
                              cache: false,
                              success: function(result) {
                                 $('#jobGroupNav').html(result);
                                 $("label.key").each(function(i, el) { beautifyTableCaption(el); });
                              }
                           });
                        }
                     });
                  }
               } else {
                  showMessagePanel(result.data.message, target, true, {placement:'right'});
               }
            }
         });
      }, function(){
         $('#manageJobGroupModal').removeClass('sleeping').modal('show');
      });
   });

   //增加统计时间选择条 在各种情况下 需要定位 交互JS
   function repTimePosition(){
      var scrolltops = $(window).scrollTop();
      var repwidth = $(".rep_summaryrep:visible").width();
      var jobGroupNav = $("#jobGroupNav").length;
      var slscroll,sltops,slleft;
      if(jobGroupNav > 0){
         slscroll = 166;
         sltops = 114;
         slleft = 124;
      }
      else{
         slscroll = 66;
         sltops = 84;
         slleft = 137;
      }
      if(scrolltops >= slscroll){
         $(".rep_timearea").css({
            position:"fixed",
            top:sltops+"px",
            zIndex:103,
            left:slleft+"px",
            width:repwidth,
         })
      }
      else{
         $(".rep_timearea").css({
            position:"static",
            width:"auto",
         })
      }
   }
   $(window).scroll(function(){
      repTimePosition();
   });
   
});